/* eslint-disable no-var */
/* 随机数范围 */
export function random(min, max) {
  if (arguments.length === 2) {
    return Math.floor(min + Math.random() * ((max + 1) - min))
  }
  return undefined
}


/*
  使用方法：
  Money（value,num）的第一位value是必传的，第二位num是选填的 不填是保留两位小数
  console.log(Money('123456789',2))  -->123,456,789.00
*/
export function parseMoney(val) {
  // eslint-disable-next-line no-use-before-define
  return numberFormat(val, 2)
}

/*
 * 参数说明：
 * number：要格式化的数字
 * decimals：保留几位小数
 * deCpoint：小数点符号
 * thousandSep：千分位符号
 * */
export function numberFormat(number, decimals, deCpoint, thousandSep) {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  const n = !isFinite(+number) ? 0 : +number
  const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
  const sep = (typeof thousandSep === 'undefined') ? ',' : thousandSep
  const dec = (typeof deCpoint === 'undefined') ? '.' : deCpoint
  let s = ''
  // eslint-disable-next-line no-shadow
  const toFixedFix = function (n, prec) {
    // eslint-disable-next-line no-restricted-properties
    const k = Math.pow(10, prec)
    return '' + Math.ceil(n * k) / k
  }

  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  const re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}


// 1. `randomIntegerInRange`：生成指定范围的随机整数
export const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
// randomIntegerInRange(0, 5); // 3

// 2. `randomNumberInRange`：生成指定范围的随机小数
export const randomNumberInRange = (min, max) => Math.random() * (max - min) + min
// randomNumberInRange(2, 10); // 6.0211363285087005

// 3. `round`：四舍五入到指定位数
export const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`)
// round(1.005, 2); // 1.01

// 4. `sum`：计算数组或多个数字的总和
export const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0)
// sum(1, 2, 3, 4); // 10
// sum(...[1, 2, 3, 4]); // 10

// 5. `toCurrency`：简单的货币单位转换
export const toCurrency = (n, curr, LanguageFormat = undefined) => Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n)
// toCurrency(123456.789, 'EUR'); // €123,456.79
// toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79
// toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹
// toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423

// `Random Hexadecimal Color Code`：随机十六进制颜色
export const randomHexColorCode = () => {
  const n = (Math.random() * 0xfffff * 1000000).toString(16)
  return '#' + n.slice(0, 6)
}
// randomHexColorCode(); // "#e34155"
